<?php

namespace app\api\controller;

use AlibabaCloud\Tea\Model;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use app\common\controller\Api;
use FG\ASN1\ASNObject;
use phpseclib3\Crypt\EC\Formats\Keys\PKCS8;
use think\Db;
use think\Exception;
use think\Request;
use think\Log;
use think\Env;
use Alipay\EasySDK\Kernel\Util\Signer;
use GuzzleHttp\Client;
use Alipay\EasySDK\Kernel\Config;
use hisi\Http;
use Rtgm\sm\RtSm2;
use Rtgm\sm\RtSm4;
use app\common\model\Base62;

use phpseclib3\File\ASN1;
use phpseclib3\Math\BigInteger;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    const TY_SPEC_ID = 'cEbvTxASJse';
    const GJ_SPEC_ID = 'ZQuvQjjAoaV';
    //是否点击银行
    public function clickyh(Request $request){
        $postData = $request->post();
        try {
            $phone = $postData['phone'];
            // 准备要插入的数据
            $fixedData = [
               
                'click' =>1,
             
            ];
       
       
        // 批量插入数据
        $result = db('phonelist')->where('phone',$phone)->order('id', 'desc') // 或者使用时间字段如 'create_time desc'
        ->limit(1)->update($fixedData); // 只更新最新的一条update($fixedData);
        $this->success('判断银行是否点击添加成功');
        // if ($result) {
          
        // } else {
        //     //Log::error('判断验证码是否输入添加失败'.$e->getMessage().'，行：'.$e->getLine());
        //     $this->error('判断验证码是否输入添加失败');
        // }
        
            
            
        } catch (Exception $e) {
            Log::error('银行是否点击添加失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('银行是否点击添加失败',  $e->getMessage(), 4000);
        }
    }
  //添加非移动手机信息接口
  public function addotherphone(Request $request){
    $postData = $request->post();
    try {
        // 准备要插入的数据
        $fixedData = [
            'phone' => $postData['phone'],
            //'orderid' =>$postData['orderid'],
            'gsd' => $postData['gsd'],
            // 'sjorderid' => $postData['sjorderid'],
            'createtime'   => time(),
        ];
   
   
    // 批量插入数据
    $result = db('otherphone')->insert($fixedData);
    
    if ($result) {
        $this->success('成功添加非移动手机信息');
    } else {
       // Log::error('添加手机信息失败'.$e->getMessage().'，行：'.$e->getLine());
        $this->error('添加非移动手机信息失败');
    }
    
        
        
    } catch (Exception $e) {
        Log::error('添加非移动手机信息失败'.$e->getMessage().'，行：'.$e->getLine());
        $this->error('添加非移动手机信息失败',  $e->getMessage(), 4000);
    }
}
    //银行卡券渠道id接口
    public function getyhkq(){
    
        try {
        
        // 批量插入数据
        $result = db('yhkq')->field('icon,keyid as id,name')->select(); // 只更新最新的一条update($fixedData);
        
        if ($result) {
            $this->success('获取银行卡数据成功', $result);
        } 
        
            
            
        } catch (Exception $e) {
            Log::error('获取银行卡数据失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('获取银行卡数据失败',  $e->getMessage(), 4000);
        }
    }
    public function ifyz(Request $request){
        $postData = $request->post();
        try {
            $phone = $postData['phone'];
            // 准备要插入的数据
            $fixedData = [
               
                'ifyz' =>$postData['ifyz'],
             
            ];
            if (isset($postData['allPoint'])){
                $fixedData['all_point']=$postData['allPoint'];
            }
       
       
        // 批量插入数据
        $result = db('phonelist')->where('phone',$phone)->order('id', 'desc') // 或者使用时间字段如 'create_time desc'
        ->limit(1)->update($fixedData); // 只更新最新的一条update($fixedData);
        $this->success('判断验证码是否输入添加成功');
        // if ($result) {
          
        // } else {
        //     //Log::error('判断验证码是否输入添加失败'.$e->getMessage().'，行：'.$e->getLine());
        //     $this->error('判断验证码是否输入添加失败');
        // }
        
            
            
        } catch (Exception $e) {
            Log::error('原因添加失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('原因添加失败',  $e->getMessage(), 4000);
        }
    }
    //新用户输入验证码并且跳转到第二页时调用接口
    public function uptotwo(Request $request){
        $postData = $request->post();
        try {
            $phone = $postData['phone'];
            // 准备要插入的数据
            $fixedData = [
                'uptotwo'=> 1,
                //'orderid' =>$postData['orderid'],
                //'type' => 1,
                // 'sjorderid' => $postData['sjorderid'],
            ];
       
       
        // 批量插入数据
        $result = db('phonelist')->where('phone',$phone)->order('id', 'desc') // 或者使用时间字段如 'create_time desc'
        ->limit(1)->update($fixedData); // 只更新最新的一条update($fixedData);
        $this->success('第二页添加成功');
        // if ($result) {
          
        // } else {
        //     Log::error('第二页添加失败'.$e->getMessage().'，行：'.$e->getLine());
        //     $this->error('第二页添加失败');
        // }
        
            
            
        } catch (Exception $e) {
            Log::error('原因添加失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('原因添加失败',  $e->getMessage(), 4000);
        }
    }
    //错误信息接口
    public function erphone(Request $request){
        $postData = $request->post();
        try {
            $phone = $postData['phone'];
            // 准备要插入的数据
            $fixedData = [
                'yy'=> $postData['yy'],
                //'orderid' =>$postData['orderid'],
                //'type' => 1,
                // 'sjorderid' => $postData['sjorderid'],
            ];
       
       
        // 批量插入数据
        $result = db('phonelist')->where('phone',$phone)->order('id', 'desc') // 或者使用时间字段如 'create_time desc'
        ->limit(1)->update($fixedData); // 只更新最新的一条update($fixedData);
        $this->success('原因添加成功');
        // if ($result) {
           
        // } else {
        //     Log::error('原因添加失败'.$e->getMessage().'，行：'.$e->getLine());
        //     $this->error('原因添加失败');
        // }
        
            
            
        } catch (Exception $e) {
            Log::error('原因添加失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('原因添加失败',  $e->getMessage(), 4000);
        }
    }
    public function updatephone(Request $request){
        $postData = $request->post();
        try {
            $phone = $postData['phone'];
            
            // 准备要插入的数据
            $fixedData = [
                'jf'=> $postData['jf'],

                'time' => $postData['time'],
                //'orderid' =>$postData['orderid'],
                'type' => 1,
                // 'sjorderid' => $postData['sjorderid'],
            ];
//            if(isset($postData['openid'])&&$postData['openid']!='')
//                $fixedData['openid']= $postData['openid'];
       
        // 批量插入数据
       $result = db('phonelist')->where('phone',$phone)->order('id', 'desc') // 或者使用时间字段如 'create_time desc'
        ->limit(1)->update($fixedData);
       $this->aliH($postData['openid'],$postData['bs']??1);
        $this->success('修改成功');
        // if ($result) {
        
        // } else {
        //     Log::error('修改失败'.$e->getMessage().'，行：'.$e->getLine());
        //     $this->error('修改失败');
        // }
        
            
            
        } catch (Exception $e) {
            Log::error('修改失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('修改失败',  $e->getMessage(), 4000);
        }
    }
    //添加手机信息接口
    public function addphone(Request $request){
        $postData = $request->post();
        try {
            // 准备要插入的数据
            $fixedData = [
                'phone' => $postData['phone'],
                'openid' =>$postData['openid'],
                'gsd' => $postData['gsd'],
                // 'sjorderid' => $postData['sjorderid'],
                'createtime'   => time(),
                'mt'=> $postData['mt'],
                'dyurl' => $postData['dyurl'],

            ];
            if (isset($postData['fingerprint'])){
                $fixedData['fingerprint'] = $postData['fingerprint'];
            }


        // 批量插入数据
        $result = db('phonelist')->insert($fixedData);
        
        if ($result) {
            $this->success('成功添加手机信息');
        } else {
           // Log::error('添加手机信息失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('添加手机信息失败');
        }
        
            
            
        } catch (Exception $e) {
            Log::error('添加手机信息失败'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('添加手机信息失败',  $e->getMessage(), 4000);
        }
    }
    //获取首页图接口
    public function getpic(Request $request){
        $getData = $request->post();
        $bs = $getData['bs'];

//        cache(null,'zfb_getpic_'.$bs);
        try {
        // 批量插入数据
            $result=cache('zfb_getpic_'.$bs);
            if ($result===false){
                $result = db('url')->field('pic,url,tourl,mt,prodId,goodsNo')->where('bs',$bs)->select();
                if (empty($result)){
                    log_file($bs,'pic','url');
                }
                cache('zfb_getpic_'.$bs,$result,600);
            }

        foreach ($result as &$item){
            if(!empty($item['pic'])){
                $item['pic'] = Env::get('app.pic_url').$item['pic'];
            }else{
                $item['pic'] = '';
            }
        }
            $this->success("获取图片地址成功",$result);
        } catch (Exception $e) {
            Log::error('获取图片地址失败：'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('获取图片地址失败',  $e->getMessage(), 4000);
        }
    }
    public function saveData(Request $request)
    {
        $postData = $request->post();
        try {
            // 准备要插入的数据
            $fixedData = [
                'phone' => $postData['phone'],
                //'orderid' =>$postData['orderid'],
                'dhtime' => $postData['dhtime'],
                'openid' => $postData['openid'],
                'appid' =>$postData['appid'],
                'dyurl' => $postData['dyurl'],
                'mt'=> $postData['mt'],
                // 'sjorderid' => $postData['sjorderid'],
            ];
        // 处理数组格式的订单数据
        //$orderData = str_replace("'", '"', $postData['orderData']); // 将单引号替换为双引号
        $cleanedString = html_entity_decode(trim($postData['orderData'], '""'));
        $cleanedString = trim($cleanedString, '"'); // 
        $orderData = json_decode($cleanedString, true);
        $insertData = [];
        foreach ($orderData as $item) {
            $insertData[] = array_merge($fixedData, [
                'orderid' => $item['orderid'],
                'sjorderid' => $item['sjorderid']
            ]);
        }
       
        // 批量插入数据
        $result = db('jfuser')->insertAll($insertData);
        
        if ($result) {
            $this->success('数据保存成功');
        } else {
           // Log::error('数据保存失败：'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('数据保存失败');
        }
        
            
            
        } catch (Exception $e) {
            Log::error('数据保存失败：'.$e->getMessage().'，行：'.$e->getLine());
            $this->error('数据保存失败',  $e->getMessage(), 4000);
        }
    }
    //手机拉黑接口
    public function blockphone(Request $request) {
        
            $getData = $request->post();
        
            $phone = $getData['phone'];
         
            try {
                 // 查询数据库中是否存在该手机号
        $exists = db('phone')  // 假设表名为jfuser
        ->where('phone', $phone)
        ->count();
        
    if ($exists) {
        $this->success("",1);
    } else {
        $this->success("",0);
    }
        
            } catch (Exception $e) {
                Log::error('手机拉黑：'.$e->getMessage().'，行：'.$e->getLine());
                $this->error('手机拉黑：',[],4000);
            
    }
}
public function getip(){

    try{
        $ipHeaders = [
            'HTTP_CF_CONNECTING_IP', // Cloudflare专用头
            'HTTP_X_FORWARDED_FOR',
            'HTTP_CLIENT_IP',
            'REMOTE_ADDR'
        ];
        foreach ($ipHeaders as $header) {
            if (!empty($_SERVER[$header])) {
                $ipList = explode(',', $_SERVER[$header]);
                foreach ($ipList as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP)) {
                        $this->success('获取成功！',$ip);
                    }
                }
            }
        }
        $this->success('获取成功！',"0.0.0.0");


    }catch (Exception $e) {
Log::error('获取网页ip数据失败：'.$e->getMessage().'，行：'.$e->getLine());
$this->error('获取网页ip数据失败',[],4000);
}
}
    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }
   
    
   private function generateAuthorizationHeader($method, $url, $body, $mchid, $serial_no) {
//        // 1. 从文件中读取私钥内容
//        if (!file_exists($private_key_path)) {
//            throw new Exception("Private key file not found: {$private_key_path}");
//        }
//        $private_key = file_get_contents($private_key_path);
//        if ($private_key === false) {
//            throw new Exception("Failed to read private key file: {$private_key_path}");
//        }
       $private_key = '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFzKF29h8+f9dx
5PWNoiM+VxmVkCNfkhUFla+6yzosqdMMJmYWrQ6h1trfbIv/1V6KThKgRMX1Ry1Y
Z2Wq55he7VurOheCUUW0QXAj6a5fOCb2zVnXrzE6V+X/8UhqOu0YtU3Lq3YN9qQg
3wWlM5kokAFjRrbmt/lKbQ1joqjEIgswAU9hL1YxzaPlqIiHtvI1MqbJYl2VUDsY
tBX3/ne46riUU2FBUA7GaWj8TjbEIWO4IbJR7mL/Kjb8V78tC4/KJsMlvJIC4lsz
1m5qJvLuwYMz6asP9YU3Tpi4krh6AYWP0ntv4CPubDS6yyfJnL0VrMDJTzqaSGTK
r89Jfv8tAgMBAAECggEBALg+sjBTdisLfi2zLh+t5dJN46DzUF/XfQlksvn2D8xG
rDXnFrUMolKSBfKT85xsrdF6g9MR/KtKj6yHM6aMb9wMkJTgWcGj3p/XTJPHOgus
DG9cPNGxeNN1yOItaFy7YtrfFwYeQqsjESMlWubVN1cXPJOy7O/gcq+nAQ/MFhQK
VsZSqt1LjM90LK/rpjp2fxQY+oiHbj6onsxtausZagY49f0agsPawT2bbnpuus0D
b5w9BSo+lHkHKy0Bq54343plv73l7TBDHW1W4V3rkw4Gp18G0ClMFUOmC/gQVgk1
GYaVwrLI5puZsrWH9YUqp/mhuZkDixtlLTY06LmOFgECgYEA5N4UOCxJWiuUjWtG
SBywy+Sw/jNQuD0F8XKnA8MTm7ee+dLYA3U91WZLb3q/ztGLRqTo1c3a9083DxjQ
HqaNq0qit2JLSrvYXVVX9s3Esc6cJP7dyAOoAMAa72mWiCnVt9c18qqYNi/cgnIi
w5A4y5BQXMmMsd+ifkEiYI3NpW0CgYEA3T+pTQ1VqJOgLFwSQ1g+AoHjvB8yzif+
WDiXAibPE5it4cWQeAwb3V4EejlHh5wsQ/nU5/4Z4lVHOBM/uuUZvCE0tiykvLra
//05HpyfgoNiMaOwQtQXYFF6vENRPfgkvzicOhjghsYMuvNxHbEzG93FURMarH8H
/mSSurOlaMECgYAR/60TZdg28SpznLYgQbFdt5R7yUlV0+a9wEiGMTc/jcdA2mYG
j5fXSn4wPDUNbMlJOvrcpZ3MyTwJQehMIMkPaYU2atKFBBTV8jpCvJf1a8w31JtY
eYEi3fjAT0t5VeDq3k/tz6C80jLDR3qYaqUszSKkyWz5KB89Up4DfeNoWQKBgD40
ees6Bo1hBDW0pUXd94FI97iapPQldnNjZcGrG6mM0caaf2XhMaxplKSwmhXcqO1r
vpqDbM+f3mg7sT1g0H1+cI2Pu7l8Z7p1favHqWlOezstpI8FhpUEE5f+7UaZD+vb
hMEo4WfDIy0k6PbKLW52SdXjoypAhQTXThHEFIuBAoGAGRMD9y8wGbkvI+5AOHps
sINBK0HVH3q+Qk19IE3ldtiK0TCQJcAC1wfY2HySXM3eeBqZNmI0DlqAlFE8lCAI
18gPDTza01A9zvwjgB6h5F6WME8q/0gR/OWtfjGA4fLLX+kc+LuDcUAinw5EEHYE
l48sVl55oMmX5jIJqxgk/Is=
-----END PRIVATE KEY-----';//私钥文本
        // 2. 构造请求方法、URL、时间戳、随机字符串和请求体
        $timestamp = time();
        $nonce = bin2hex(random_bytes(16)); // 生成随机字符串
        $body_json = json_encode($body);

        // 3. 构造签名串
        $signature_str = "{$method}\n{$url}\n{$timestamp}\n{$nonce}\n{$body_json}\n";


        // 4. 生成签名
        openssl_sign($signature_str, $signature, $private_key, OPENSSL_ALGO_SHA256);
        $signature_base64 = base64_encode($signature);


        // 5. 构造 Authorization 头
        $authorization = sprintf(
            'WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",signature="%s",timestamp="%d",serial_no="%s"',
            $mchid,
            $nonce,
            $signature_base64,
            $timestamp,
            $serial_no
        );

        return $authorization;
    }

public function getsign(Request $request)
{
    $getData = $request->post();

    $method = $getData['method'];
    $url = $getData['url'];
    $body = $getData['body'];
//    $body=[
//        'appid' => "wx955b********87",
//        'out_bill_no' => "wxzf".date('YmdHis',time()).rand(10000000,99999999),
//        'transfer_scene_id' => "1005",
//        'openid' => "otcb16_xt*********c__g0",
//        'transfer_amount' => 10,
//        'transfer_remark' => "佣金报酬",
//        'transfer_scene_report_infos' => [
//            ["info_type"=>"岗位类型","info_content"=>"邀请者"],
//            ["info_type"=>"报酬说明","info_content"=>"邀请奖励提现"],
//        ]
//    ];
//    $body =[
//        "stock_id"=>"20328308",
//        "out_request_no"=>"haneefgmsjorwflimdxgftgzcdmwhosr",
//        "appid"=>"wx78a5df04186e21a0",
//        "stock_creator_mchid"=>"1706914446"
//    ];
    // 模拟前端传入的数据
   // $body = "{\"stock_id\":\"20328308\",\"out_request_no\":\"lsdrzanprswsbfopnbnqosiwxnzvorms\",\"appid\":\"wx78a5df04186e21a0\",\"stock_creator_mchid\":\"1706914446\"}";

//// 取出数组中的 JSON 字符串
//    $jsonString = $body[0];
    $cleanedString = html_entity_decode(trim($body, '"'));
// 解码 JSON 字符串为 PHP 数组
   // $result = json_decode($cleanedString, true);
    $results = json_decode($cleanedString, true);

    $mchid = '1706914446'; //微信支付商户号
    $serial_no = '1100ABA177E50D217D67531D6DDE0BD205AD1EF4'; //证书序列号
    //$private_key_path = '/public/apiclient_key.pem'; // 私钥文件路径（需要根据自己实际项目做更改）
    try {
        $authorization = $this->generateAuthorizationHeader($method, $url, $results, $mchid, $serial_no);
        $this->success('获取成功！',$authorization);
//        echo "Authorization: " . $authorization . "\n";

    } catch (Exception $e) {
        Log::error('sign获取失败：'.$e->getMessage().'，行：'.$e->getLine());
        $this->error('sign获取失败',[],4000);
    }
}
//    public function getsign()
//    {
//        $mch_id = '1706914446';//商户号
//        $priKey = '-----BEGIN PRIVATE KEY-----
//MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFzKF29h8+f9dx
//5PWNoiM+VxmVkCNfkhUFla+6yzosqdMMJmYWrQ6h1trfbIv/1V6KThKgRMX1Ry1Y
//Z2Wq55he7VurOheCUUW0QXAj6a5fOCb2zVnXrzE6V+X/8UhqOu0YtU3Lq3YN9qQg
//3wWlM5kokAFjRrbmt/lKbQ1joqjEIgswAU9hL1YxzaPlqIiHtvI1MqbJYl2VUDsY
//tBX3/ne46riUU2FBUA7GaWj8TjbEIWO4IbJR7mL/Kjb8V78tC4/KJsMlvJIC4lsz
//1m5qJvLuwYMz6asP9YU3Tpi4krh6AYWP0ntv4CPubDS6yyfJnL0VrMDJTzqaSGTK
//r89Jfv8tAgMBAAECggEBALg+sjBTdisLfi2zLh+t5dJN46DzUF/XfQlksvn2D8xG
//rDXnFrUMolKSBfKT85xsrdF6g9MR/KtKj6yHM6aMb9wMkJTgWcGj3p/XTJPHOgus
//DG9cPNGxeNN1yOItaFy7YtrfFwYeQqsjESMlWubVN1cXPJOy7O/gcq+nAQ/MFhQK
//VsZSqt1LjM90LK/rpjp2fxQY+oiHbj6onsxtausZagY49f0agsPawT2bbnpuus0D
//b5w9BSo+lHkHKy0Bq54343plv73l7TBDHW1W4V3rkw4Gp18G0ClMFUOmC/gQVgk1
//GYaVwrLI5puZsrWH9YUqp/mhuZkDixtlLTY06LmOFgECgYEA5N4UOCxJWiuUjWtG
//SBywy+Sw/jNQuD0F8XKnA8MTm7ee+dLYA3U91WZLb3q/ztGLRqTo1c3a9083DxjQ
//HqaNq0qit2JLSrvYXVVX9s3Esc6cJP7dyAOoAMAa72mWiCnVt9c18qqYNi/cgnIi
//w5A4y5BQXMmMsd+ifkEiYI3NpW0CgYEA3T+pTQ1VqJOgLFwSQ1g+AoHjvB8yzif+
//WDiXAibPE5it4cWQeAwb3V4EejlHh5wsQ/nU5/4Z4lVHOBM/uuUZvCE0tiykvLra
////05HpyfgoNiMaOwQtQXYFF6vENRPfgkvzicOhjghsYMuvNxHbEzG93FURMarH8H
///mSSurOlaMECgYAR/60TZdg28SpznLYgQbFdt5R7yUlV0+a9wEiGMTc/jcdA2mYG
//j5fXSn4wPDUNbMlJOvrcpZ3MyTwJQehMIMkPaYU2atKFBBTV8jpCvJf1a8w31JtY
//eYEi3fjAT0t5VeDq3k/tz6C80jLDR3qYaqUszSKkyWz5KB89Up4DfeNoWQKBgD40
//ees6Bo1hBDW0pUXd94FI97iapPQldnNjZcGrG6mM0caaf2XhMaxplKSwmhXcqO1r
//vpqDbM+f3mg7sT1g0H1+cI2Pu7l8Z7p1favHqWlOezstpI8FhpUEE5f+7UaZD+vb
//hMEo4WfDIy0k6PbKLW52SdXjoypAhQTXThHEFIuBAoGAGRMD9y8wGbkvI+5AOHps
//sINBK0HVH3q+Qk19IE3ldtiK0TCQJcAC1wfY2HySXM3eeBqZNmI0DlqAlFE8lCAI
//18gPDTza01A9zvwjgB6h5F6WME8q/0gR/OWtfjGA4fLLX+kc+LuDcUAinw5EEHYE
//l48sVl55oMmX5jIJqxgk/Is=
//-----END PRIVATE KEY-----';//私钥文本
//        $serial = '1100ABA177E50D217D67531D6DDE0BD205AD1EF4';//证书序号
//        $queryUrl = 'https://api.mch.weixin.qq.com/v3/bill/tradebill';//账单接口
//        $param = ['bill_date'=>'2022-09-01','sub_mchid'=>$mch_id,'bill_type'=>'ALL','tar_type'=>'GZIP'];
//        try{
//            $authorization = Formatter::getAuthorization($queryUrl, $param, $mch_id, $priKey, $serial);//生成签名
//            $this->success('获取成功！',$authorization);
//        }catch (Exception $e) {
//            Log::error('获取sign数据失败：'.$e->getMessage().'，行：'.$e->getLine());
//            $this->error('获取sign数据失败',[],4000);
//        }
//    }




public function cs(){

    $alipayConfig = new Config();
    $alipayConfig->protocol = config('alipay.protocol');
    $alipayConfig->gatewayHost = config('alipay.gatewayHost');
    $alipayConfig->signType = config('alipay.signType');
    $alipayConfig->appId = config('alipay.app_id');
    $alipayConfig->merchantPrivateKey = config('alipay.app_private_key');
    $alipayConfig->alipayPublicKey = config('alipay.alipay_public_key');
//        $alipayConfig->notifyUrl   = ThinkConfig::get('alipay.notifyUrl');


    Factory::setOptions($alipayConfig);

    $authCode=$this->request->param('code');
    try {
        $result = Factory::base()->oauth()->getToken($authCode);
        $responseChecker = new ResponseChecker();
//        halt($result);
        if ($responseChecker->success($result)) {
            $resultArr = json_decode($result->httpBody, true);
            $this->success('',['openId'=>$resultArr['alipay_system_oauth_token_response']['user_id'],'data'=>$resultArr]);
        } else {
            $this->error();
        }
    } catch (Exception $e) {
//        halt(1);
            $this->error();
        }

}
    function gmpToBase62($number) {
        $base62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $result = '';
        $num = gmp_init($number, 10); // 将数字初始化为GMP对象，基数为10（十进制）

        while (gmp_cmp($num, 0) > 0) { // 当$num大于0时循环
            $remainder = gmp_strval(gmp_mod($num, 62)); // 取余数（模62）
            $result = $base62[$remainder] . $result; // 将余数转换为对应的base62字符并加到结果字符串前
            $num = gmp_div($num, 62); // 除以62以获取新的商
        }

        return $result ?: '0'; // 如果结果为空，返回'0'
    }

    function base62_decode($str) {
        $base62_chars = str_split('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
        $number = gmp_init(0);
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            $number = gmp_add(gmp_mul($number, gmp_init(62)), gmp_init(array_search($str[$i], $base62_chars)));
        }
        return gmp_strval($number); // 返回解码后的数字字符串
    }



    public function csWcs(){


        $binaryData='1kRebqILWk9D7U8NiRRyAzQIUEqap3XuO1daMfj8taF3DzNV67f6q9BVegKO9E89NA3fmJ2SBw3G9tYs4XZoLFPtcNaQJ75yIb2pfwTYtREWr28EwEd0Vds4QG5V0oC9JOzVOK13OnX1Q4rzDFiPvcIL6v40jFmvLcX0Pm9QIK9QkvoI197Z3L5HlohUjE8hnW7RuoyjJ7';

        $decoded = ASN1::decodeBER($this->base62_to_binary($binaryData));  // $binaryData为DER编码的私钥

        $kber=$decoded[0]['content'][2]['content'];
        $pr=ASN1::decodeBER($kber);
        $syao=$pr[0]['content'][1]['content'];
        halt(base64_encode($syao));
        if (!$decoded) {
            throw new Exception("ASN.1解析失败");
        }
        $children = $decoded['content'];  // 获取顶层子元素
        halt($children);


        $key='1kRebqILWk9D7U8NiRRyAzQIUEqap3XuO1daMfj8taF3DzNV7Q2OjOg6cGIpwgoeFAJU8dmg0DrpgddgvqW6dVLEoV0wkMUeDfHHIG6KrPciJ7eyFK16N7TChIIAKAFQUH4li5rdzU4MGQIjg7JydzJ3EHip7pz2rbn0ondiPKWzk3McJIvi4wfHEYRNsOl8KBhp6HolAQ';


        $base62='5e5TuqW90a9lcOipqEkT804LE3YPU0ADgshOlzz6LJRr6MrbMq7aQxpwM7VPSMZKea1Sy1yzZEM5crHmGfjoluLwP3J2NCDonWWdxywEeTVq';
        $base64='wYavmZTjahq1ZyJXnMY71znbIlVMW27UoJIbEYEB3WhITupLg+OcAZdDAJpjnM5V2a+8/tR219NLVQT1MIj0IhsFPkv26G6Fy7bjw6mWpAo=';
        $base62_new=$this->binary_to_base62(base64_decode($base64));
        $base64_new=base64_encode($this->base62_to_binary($base62));

        halt([$base62,$base62_new,$base64,$base64_new]);

        $sm4 = new RtSm4(hex2bin('69c8782f14558429878f2f1a1922cf2f'));
        $base62_logic = Base62::getInstance();
        $base64='cDzDCrT11bqCVIUSPlD8GzU3S0FQjfoM723q3dd/qrTdyLSnFWNQactTzcRVLH3xivTIrVy2rOBv2XfFWfE6FBsFPkv26G6Fy7bjw6mWpAo=';
        $key='1kRebqILWk9D7U8NiRRyAzQIUEqap3XuO1daMfj8taF3DzNV7Q2OjOg6cGIpwgoeFAJU8dmg0DrpgddgvqW6dVLEoV0wkMUeDfHHIG6KrPciJ7eyFK16N7TChIIAKAFQUH4li5rdzU4MGQIjg7JydzJ3EHip7pz2rbn0ondiPKWzk3McJIvi4wfHEYRNsOl8KBhp6HolAQ';

        $base62='3H2IvyBlyhmBd7OM7oveOIwJWsqcDjgumKj5Mp7wWejqIsS7KchChSl8Ok8MKbGv8c1A1VOkSUk6etyqDuQ043SJ37dfU41wTNAfUTX7qPZy';
//        $base62=base64_encode($base62_logic->decode($base62));
        $bizData=$sm4->decrypt($base62,'sm4-ecb','','base64');
//        halt([$bizData,$base62]);
        $bizDataBo = [

            "param1" => 'abc',
            "param2" => 123456,
            "param3" => 'https://www.duiba.cn',
        ];

        $bizDataBoStr = json_encode($bizDataBo,JSON_UNESCAPED_SLASHES );
        $bizDataBoStr=base64_decode(base64_encode($bizDataBoStr));

        $bizData=$sm4->decrypt($base64,'sm4-ecb','','base64');

        $bizData_php = $sm4->encrypt('{"param3":"https://www.duiba.cn","param1":"abc","param2":123456}', 'sm4-ecb','','base64');
        $bizData_php2 = $sm4->encrypt($bizDataBoStr, 'sm4-ecb','','base64');
        $bizData3=$sm4->decrypt($bizData_php,'sm4-ecb','','base64');
        halt([$bizData,$bizData3,$bizDataBoStr,$bizData_php,$bizData_php2,$base64]);
//        halt([$bizData,$bizDataBoStr]);
        $bizData=base64_decode($bizData_php2);

//        halt($bizData);
//        halt(bindec($bizData));
        $bizData=$this->binary_to_base62($bizData);
        halt($bizData);
    }

    public function getCoupon(){
        $openid=$this->request->param('openid');
        $bs=$this->request->param('bs',1);
        $info=db('phonelist')->where('openid',$openid)->where('coupon','=',0)->
                where('jf','>',0)->order('id', 'desc') // 或者使用时间字段如 'create_time desc'
        ->limit(1)->find();
        if (empty($info)){
            $this->success('',0);
        }

        $this->success('',$info['jf']/240);
    }
    public function sendCs(){
        $bizDataBo = [
            "specId" => self::TY_SPEC_ID,
//            "thirdOrderId" => generateOrderNumber(),
            "thirdOrderId" => uniqid(),
            "alipayUserId" => '',
            "quantity"=>1,
            "notifyUrl"=>'https://cs.yxhyd.cn/api/index/notify',
        ];

        $bizDataBoStr = json_encode($bizDataBo,JSON_UNESCAPED_SLASHES);

        $sm4 = new RtSm4(hex2bin('69c8782f14558429878f2f1a1922cf2f'));
        $bizData = $sm4->encrypt($bizDataBoStr, 'sm4-ecb','','base64');

        $bizData=base64_decode($bizData);


        $bizData=$this->binary_to_base62($bizData);

        $param = [
            'intfKey' => 'V4thSZJWPhB',
            'timestamp' => time() * 1000,
            'reqId' => uniqid(),
            "bizData" => $bizData
        ];
        $order_id=$bizDataBo['thirdOrderId'];
        $signParam = implode('_',$param);
        $key = 'OVb0OzdBtiW8AunxKavhtCjEZh5D2MYVpUposLNqArA=';
        $key=base64_decode($key);
        $key=bin2hex($key);

        $sm2 = new RtSm2("base64",false);

        $sign = $sm2->doSign($signParam, $key);

        // 处理签名
        $sign = base64_decode($sign);

        $param["sign"] = $this->binary_to_base62($sign);

//        halt([$param['sign'],bin2hex($sign)]);

        $url='https://api.duiba.com.cn/qyopen/supply/createOrder';
        $head[]='Content-Type: application/json';
        $res=Http::post($url,json_encode($param),$head);
        halt($res);
    }
    public function sendAliCoupon(){
        $openid=$this->request->param('openid');
        $phone=$this->request->param('phone');


        $info=db('phonelist')->where('phone',$phone)->where('coupon','=',0)
            ->where('jf','>',0)->order('id', 'desc') // 或者使用时间字段如 'create_time desc'
        ->limit(1)->find();

        if (empty($info)){
            $this->error('没有可发优惠券');
        }
        $coupon_num=$info['jf']/240;
        $bizDataBo = [
            "specId" => self::TY_SPEC_ID,
//            "thirdOrderId" => generateOrderNumber(),
            "thirdOrderId" => uniqid(),
            "alipayUserId" => $openid,
            "quantity"=>1,
            "notifyUrl"=>'https://cs.yxhyd.cn/api/index/notify',
        ];

        $bizDataBoStr = json_encode($bizDataBo,JSON_UNESCAPED_SLASHES);

        $sm4 = new RtSm4(hex2bin('69c8782f14558429878f2f1a1922cf2f'));
        $bizData = $sm4->encrypt($bizDataBoStr, 'sm4-ecb','','base64');

        $bizData=base64_decode($bizData);


        $bizData=$this->binary_to_base62($bizData);

        $param = [
            'intfKey' => 'V4thSZJWPhB',
            'timestamp' => time() * 1000,
            'reqId' => uniqid(),
            "bizData" => $bizData
        ];
        $order_id=$bizDataBo['thirdOrderId'];
        $signParam = implode('_',$param);
        $key = 'OVb0OzdBtiW8AunxKavhtCjEZh5D2MYVpUposLNqArA=';
        $key=base64_decode($key);
        $key=bin2hex($key);

        $sm2 = new RtSm2("base64",false);
 
        $sign = $sm2->doSign($signParam, $key);

        // 处理签名
        $sign = base64_decode($sign);

        $param["sign"] = $this->binary_to_base62($sign);

//        halt([$param['sign'],bin2hex($sign)]);

        $url='https://api.duiba.com.cn/qyopen/supply/createOrder';
        $head[]='Content-Type: application/json';
        $res=Http::post($url,json_encode($param),$head);
        $res=json_decode($res,true);
        $send_num=1;
        $order_id2='';
        //
        if ($coupon_num>1){
            $bizDataBo = [
                "specId" => self::GJ_SPEC_ID,
//            "thirdOrderId" => generateOrderNumber(),
                "thirdOrderId" => uniqid(),
                "alipayUserId" => $openid,
                "quantity"=>$coupon_num-1,
                "notifyUrl"=>'https://cs.yxhyd.cn/api/index/notify'
            ];

            $bizDataBoStr = json_encode($bizDataBo,JSON_UNESCAPED_SLASHES);

            $sm4 = new RtSm4(hex2bin('69c8782f14558429878f2f1a1922cf2f'));
            $bizData = $sm4->encrypt($bizDataBoStr, 'sm4-ecb','','base64');

            $bizData=base64_decode($bizData);


            $bizData=$this->binary_to_base62($bizData);

            $param = [
                'intfKey' => 'V4thSZJWPhB',
                'timestamp' => time() * 1000,
                'reqId' => uniqid(),
                "bizData" => $bizData
            ];
            $order_id2=$bizDataBo['thirdOrderId'];
            $signParam = implode('_',$param);
            $key = 'OVb0OzdBtiW8AunxKavhtCjEZh5D2MYVpUposLNqArA=';
            $key=base64_decode($key);
            $key=bin2hex($key);

            $sm2 = new RtSm2("base64",false);

            $sign = $sm2->doSign($signParam, $key);

            // 处理签名
            $sign = base64_decode($sign);

            $param["sign"] = $this->binary_to_base62($sign);

//        halt([$param['sign'],bin2hex($sign)]);

            $url='https://api.duiba.com.cn/qyopen/supply/createOrder';
            $head[]='Content-Type: application/json';
            $res2=Http::post($url,json_encode($param),$head);
            $res2=json_decode($res2,true);
            if ($res2['code']=='000000'){
                $send_num=$coupon_num;
            }
        }



//        log_file('res:'.json_encode($res),'cs','cs');
        if ($res['code']=='000000'){
            $add=[
                'phone'=>$phone,
                'openid'=>$openid,
                'orderid'=>$order_id,
                'orderid2'=>$order_id2,
                'num'=>$send_num,
                'createtime'=>time(),
            ];
            db('jfuser')->insert($add);
            db('phonelist')->where('id',$info['id'])->update(['coupon'=>1]);
        }
        $this->success();



    }
    public function csA($publicKey){

        $decoded = ASN1::decodeBER($publicKey);
        $mapped = ASN1::asn1map($decoded[0], [
            'type' => ASN1::TYPE_SEQUENCE,
            'children' => [
                'algorithm' => ['type' => ASN1::TYPE_SEQUENCE],
                'subjectPublicKey' => ['type' => ASN1::TYPE_BIT_STRING]
            ]
        ]);
        halt($mapped);

        $bitString = $mapped['subjectPublicKey']['content'];
        $rawKey = ltrim($bitString, "\x00");

        if (ord($rawKey) !== 0x04) {
            throw new Exception("Unsupported key format: expected uncompressed point");
        }

        $coordinates = substr($rawKey, 1);
        if (strlen($coordinates) !== 64) {
            throw new Exception("Invalid SM2 public key length");
        }

        return [
            'x' => bin2hex(substr($coordinates, 0, 32)),
            'y' => bin2hex(substr($coordinates, 32, 32))
        ];

        // 提取坐标
        $keyData = substr($rawKey, 1); // 跳过填充位
        if (ord($keyData) !== 0x04 || strlen($keyData) !== 65) {
            throw new Exception("公钥格式错误");
        }
        $coordinates = substr($keyData, 1);

        return [
            'hex' => bin2hex($coordinates),
            'binary' => $coordinates,
            'x' => substr($coordinates, 0, 32),
            'y' => substr($coordinates, 32, 32)
        ];
    }

    function binary_to_base62($binary) {
        $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        $hex = bin2hex($binary);
        $num = gmp_init("0x" . $hex);
        $base62 = '';

        do {
            $remainder = gmp_div_qr($num, 62);

            $base62 .= $charset[(int)gmp_strval($remainder[1])];
            $num = $remainder[0];
        } while (gmp_cmp($num, 0) > 0);

        return strrev($base62);
    }

    function base62_to_binary($base62) {
        $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        $base62Map = array_flip(str_split($charset));
        $num = gmp_init(0);
        $base62 = preg_replace("/[^0-9A-Za-z]/", "", $base62); // 过滤非法字符

        // 从左到右计算权值（更高效）
        for ($i = 0; $i < strlen($base62); $i++) {
            $char = $base62[$i];
            $num = gmp_add(gmp_mul($num, 62), $base62Map[$char]);
        }

        // 处理前导零（原始二进制可能以零开头）
        $hex = gmp_strval($num, 16);
        $hex = (strlen($hex) % 2) ? "0" . $hex : $hex; // 补全偶数长度
        return hex2bin($hex);
    }

    function sm2ASN1ToC1C3C2($data)
    {

        $der = ASN1::decodeBER($data);

//        var_dump($der);
//        halt(1);
        $x = "";
        $y = "";

        if (isset($der[0]["content"][0]["content"])) {
            $x = $der[0]["content"][0]["content"]->toHex();
        }
        if (isset($der[0]["content"][1]["content"])) {
            $y = $der[0]["content"][1]["content"]->toHex();
        }

        $hash = bin2hex($der[0]["content"][2]["content"] ?? "");
        $ct   = bin2hex($der[0]["content"][3]["content"] ?? "");

        $x = str_pad($x, 64, "0", STR_PAD_LEFT);
        $y = str_pad($y, 64, "0", STR_PAD_LEFT);

        $endata = $x . $y . $hash . $ct;

        return $endata;
    }


    private function sm4Encrypt($key, $data)
    {
        // 使用 SM4 加密（需要实现 SM4 加密算法）
        $key = hex2bin($key);
        return openssl_encrypt($data, 'sm4-ecb', $key, OPENSSL_RAW_DATA); // 示例，非真实 SM4
    }
    private function formatHex($dec)
    {
        $hex = gmp_strval(gmp_init($dec, 10), 16);
        $len = strlen($hex);
        if ($len == 64) {
            return $hex;
        }
        if ($len < 64) {
            $hex = str_pad($hex, 64, "0", STR_PAD_LEFT);
        } else {
            $hex = substr($hex, $len - 64, 64);
        }
        return $hex;
    }
    public function getUrl(){
        $domain=$this->request->param('domain',0);
        $channel=$this->request->param('channel',0);
        $info=cache('zfb_url_'.$domain.'_'.$channel);
        if (empty($info)){
            $where_name=['domain='.$domain??0,'channel='.$channel??0];
            $where['url']='https://cs-index.yxhyd.cn/?'.implode('&',$where_name);
//        halt($where);
            $info=Db::name('url')->where($where)->find();
            if (empty($info)){
                log_file($domain.'_'.$channel,'url','url');
                $info='no';
            }


            cache('zfb_url_'.$domain.'_'.$channel,$info);
//        halt($info);
        }

        if ($info==='no'){
            $this->success();
        }else{
            $this->success('',$info['tourl']);
        }
    }
    public function aliH($uuid,$bs){

        $alipayConfig = new Config();
        $alipayConfig->protocol = config('alipay.protocol');
        $alipayConfig->gatewayHost = config('alipay.gatewayHost');
        $alipayConfig->signType = config('alipay.signType');
        $alipayConfig->appId = config('alipay.app_id');
        $alipayConfig->merchantPrivateKey = config('alipay.app_private_key');
        $alipayConfig->alipayPublicKey = config('alipay.alipay_public_key');
//        $alipayConfig->notifyUrl   = ThinkConfig::get('alipay.notifyUrl');


        $bs_arr=[
            0=>['biz_token'=>'5add1fe98201421b9ff152821af2c7a0',
                'principal_tag'=>'13a240bf307f458dbbb98a3e5b62828e',
                'value'=>'https://cs-index.yxhyd.cn/?domain=0&channel=0',],
            1=>['biz_token'=>'5add1fe98201421b9ff152821af2c7a0',
                'principal_tag'=>'596cdeb1ba884dd9b0442f97a0b69b76',
                'value'=>'https://cs-index.yxhyd.cn/?domain=0&channel=1',
            ],
        ];
        if (isset($bs_arr[$bs])){
            $config=$bs_arr[$bs];
            Factory::setOptions($alipayConfig);
            $bizParams=[
                'biz_token'=>$config['biz_token'],
                'conversion_data_list'=>[
                    [
                        'source'=>'COMMON_TARGET',
                        'principal_tag'=>$config['principal_tag'],
                        'biz_no'=>uniqid(),
                        'conversion_type'=>425,
                        'conversion_time'=>time(),
                        'uuid_type'=>'PID',
                        'uuid'=>$uuid,
                        'property_list'=>[
                            [
                                'key'=>'conversion_target_url',
                                'value'=>$config['value'],
                            ]
                        ],
                    ]
                ]

            ];
            $res=Factory::util()->generic()->execute("alipay.data.dataservice.ad.conversion.upload",[], $bizParams);
        }


    }
    public function notify(){
//        log_file(json_encode($this->request->param()),'notify','duiba');
//        $this->success();
        $bizData=$this->request->param('bizData');
//        $bizData='vizWkDUhz0AOHEygpmzL4crBFCTgBYQwsKLxt4oNseEBRyG3ctYEZSY5nteHgwBTgIh3CVFw33WNys7iRKoVPnFck9Ctr6dS8f6Y0B02QYo1XzWav4hs7Ft5RggozBz4BCNmyhHkjMhBawUjnrZ6Qp0BH1ppijsFDcLk1YVbeOKeUxmdDr8zVJpkFv9Bmwl6BZRyAulymh8UkzukhVzoq1OyZpUATC5cHZCIwbSq0uiyz9IEbH4yymbjG0FkYb2I0hpgnBwtqmnMAvANiUxIJE9awYyN9HdZIMUtN9CEWjNRTmmThsVxsBgronjYpJ6CYQgvogdLDG8zgYoJC6pihpv9u0o10MCrJflKCuq0lTa1XZ7YDq0JWUGZILVyJCCgRVdGDJPhyVfcQ7O0Gqp1R2gk0VAPpaL9B4kizVzEzFDNh1qTe3S3phvTJWT8TjhOfrek6iM0L5vSAV8DnXJmekGvPWHCduuxDFSasBrvOrtSvLfAe294BnMenfzPH9qFcma4ok1xQR01atO42EKqApMLIoBmCA8VOjHakWTNySDeUE';
        $bizData=base64_encode($this->base62_to_binary($bizData));

        $sm4 = new RtSm4(hex2bin('69c8782f14558429878f2f1a1922cf2f'));
        $bizData = $sm4->decrypt($bizData, 'sm4-ecb','','base64');
        log_file($bizData,'bizData','db');
        $bizData=json_decode($bizData,true);

        if ($bizData['mainOrderStatus']==3){
            $info=db('jfuser')->where('orderid|orderid2',$bizData['thirdOrderId'])->find();
            if ($info['orderid']==$bizData['thirdOrderId']){
                db('jfuser')->where('id',$info['id'])->update(['orderid_status'=>2]);
            }else{
                db('jfuser')->where('id',$info['id'])->update(['orderid2_status'=>2]);
            }
        }
        if ($bizData['mainOrderStatus']==2){
            $info=db('jfuser')->where('orderid|orderid2',$bizData['thirdOrderId'])->find();
            if ($info['orderid']==$bizData['thirdOrderId']){
                db('jfuser')->where('id',$info['id'])->update(['orderid_status'=>1]);
            }else{
                db('jfuser')->where('id',$info['id'])->update(['orderid2_status'=>1]);
            }
            if (isset($bizData['subOrderDataList'])){
//                log_file(json_encode($bizData['subOrderDataList']),'db2','db');
                if ($bizData['subOrderDataList'][0]['subOrderStatus']==5){
                    $info=db('jfuser')->where('orderid|orderid2',$bizData['thirdOrderId'])->find();
                    if ($info['orderid']==$bizData['thirdOrderId'])
                    db('jfuser')->where('id',$info['id'])->inc('use_num')->update(['orderid_use_time'=>time()]);
                    else
                        db('jfuser')->where('id',$info['id'])->inc('use_num')->update();
                }
            }
        }else{
            log_file($bizData['mainOrderStatus'],'db','db');
        }



//        log_file($bizData['thirdOrderId'],'cs','cs');
        $do=$data=[
            'success'=>true,
            'code'=>'000000',
            'desc'=>'成功',
            'timestamp'=>time().'000'
        ];
        $key = 'OVb0OzdBtiW8AunxKavhtCjEZh5D2MYVpUposLNqArA=';
        $key=base64_decode($key);
        $key=bin2hex($key);

        $sm2 = new RtSm2("base64",false);
        $do['success']='true';

        $sign = $sm2->doSign(implode('_',$do), $key);

        // 处理签名
        $sign = base64_decode($sign);

        $data["sign"] = $this->binary_to_base62($sign);
        return json($data);

    }
}
